package com.group4.blockchain.sdk;

import com.alibaba.fastjson.JSON;
import org.hyperledger.fabric.gateway.*;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeoutException;

public class InvokeSDK {
    static {
        System.setProperty("org.hyperledger.fabric.sdk.service_discovery.as_localhost", "true");
    }

    private static final String CHANNEL_NAME = "mychannel";
    private static final String CONTRACT_NAME = "mycc02_java";  //chaincode部署名称

    /**使用组织名和用户名，获取gateway连接
     * @param orgName
     * @param userName
     * @return
     * @throws IOException
     * @throws ContractException
     * @throws TimeoutException
     * @throws InterruptedException
     */
    public static Gateway getGateway(String orgName, String userName) throws IOException, ContractException, TimeoutException, InterruptedException {
        // 从wallet获得user标识
        Path walletPath = Paths.get("/home/ubuntu/workspace/app/example02_java/wallet", orgName);
        Wallet wallet = Wallets.newFileSystemWallet(walletPath);
        Identity identity = wallet.get(userName);

        // 检查wallet中是否存在user标识
        if (identity == null) {
            System.out.println("The identity \"" + userName + "@" + orgName + "\" doesn't exists in the wallet");
            return null;
        }

        //加载创建连接的tls文件
        Path networkConfigPath = Paths.get("/home/ubuntu/workspace/app/example02_java/profiles", orgName, "connection.json");
        Gateway.Builder builder = Gateway.createBuilder();
        builder.identity(wallet, userName).networkConfig(networkConfigPath).discovery(true);

        return builder.connect();

    }


    //调用sdk  ，组织名  ，用户名  ，类型  ，  方法名  ，参数
    public static String sdk(String orgName, String userName, String type, String functionName, String... args)
            throws IOException, ContractException, TimeoutException, InterruptedException {

        try (Gateway gateway = getGateway(orgName,userName)) {

            // get the network and contract
            Network network = gateway.getNetwork(CHANNEL_NAME);
            Contract contract = network.getContract(CONTRACT_NAME);
            byte[] result = null;
            if (type.equals("submit")){
                result = contract.submitTransaction(functionName, args);
            }
            else if (type.equals("evaluate")){
                result = contract.evaluateTransaction(functionName, args);
            }

            return new String(result);
        }
    }



    public static String getUserName(){
        //获取当前登录的username
        String currentUser = "";
        Object principl = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principl instanceof UserDetails) {
            currentUser = ((UserDetails)principl).getUsername();
        }else {
            currentUser = principl.toString();
        }
        return currentUser;
    }

//
//    //不需要
//    /**
//     * 调用初始化方法
//     * @param orgName
//     * @param userName
//     * @throws IOException
//     * @throws ContractException
//     * @throws TimeoutException
//     * @throws InterruptedException
//     */
//    public static void doInitChainCode(String orgName, String userName) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//            byte[] result = contract.submitTransaction("InitChainCode");
////            System.out.println(new String(result));
//        }
//    }
//
//
//
//    //清单seller  final String SellerID, final String SellerListID, final String goodID, final String goodName, final String SellerPrice
//    public static void doInitsellerList(String orgName, String userName,  String SellerID,  String SellerListID,  String goodID, String goodName,String SellerPrice) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            //final String BuyerID, final String BuyerListID, final String goodName, final String BuyerPrice
//            byte[] result = contract.submitTransaction("InitsellerList",SellerID, SellerListID,goodID,goodName,SellerPrice);
////            System.out.println(new String(result));
//        }
//    }
//
//
//    //买家心愿卡 final String BuyerID, final String BuyerListID, final String goodName, final String BuyerPrice
//    public static void doInitbuyerList(String orgName, String userName,  String BuyerID,  String BuyerListID,  String goodName, String BuyerPrice) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            //final String BuyerID, final String BuyerListID, final String goodName, final String BuyerPrice
//            byte[] result = contract.submitTransaction("InitbuyerList",BuyerID, BuyerListID,goodName,BuyerPrice);
////            System.out.println(new String(result));
//        }
//    }
//
//    //关闭心愿卡，
//    public static void doClose(String orgName, String userName,  String BuyerListID) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("Close",BuyerListID);
////            System.out.println(new String(result));
//        }
//    }
//
//
//    //查询心愿的详细信息,findkey 是指 详细信息的 key
//    public static String doQueryBuyerList(String orgName, String userName,  String BuyerListID,String findkey) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("QueryBuyerList",BuyerListID,findkey);
//            return JSON.toJSONString(result);
//        }
//    }
//
//    //能够满足清单价格的产品
//    public static String doQuerySuitable_SellerListID(String orgName, String userName,  String BuyerListID) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("QuerySuitable_SellerListID",BuyerListID);
//            return JSON.toJSONString(result);
//        }
//    }
//
//    //查询清单状态
//    public static String doQueryState(String orgName, String userName,  String BuyerListID) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("QueryState",BuyerListID);
//            return JSON.toJSONString(result);
//        }
//    }
//
//
//
//    //查询金额
//    public static void doInitMoney(String orgName, String userName,  String userID) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("InitMoney",userID);
////            System.out.println(new String(result));
//        }
//    }
//
//
//
//    //充值
//    public static void doPlusMoney(String orgName, String userName,  String userID,String changeValue) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("PlusMoney",userID,changeValue);
////            System.out.println(new String(result));
//        }
//    }
//
//
//
//    //交易支付金额
//    public static void doReducMoney(String orgName, String userName,  String userID,String changeValue) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("ReducMoney",userID,changeValue);
////            System.out.println(new String(result));
//        }
//    }
//
//
//    //选择符合条件的交易
//
//
//    //选择最符合条件的产品
//
//
//
//
//
//    //交易
//    public static void doInitTrans(String orgName, String userName,  String BuyerListID,String SellerListID) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//
//            byte[] result = contract.submitTransaction("InitTrans",BuyerListID,SellerListID);
////            System.out.println(new String(result));
//        }
//    }



    //










//    //前端需求SDK
//    //权威机构：查询所有公司信息
//    public static ArrayList getCompaniesInfo(String orgName, String userName) throws IOException, ContractException, TimeoutException, InterruptedException {
//        try (Gateway gateway = getGateway(orgName,userName)) {
//            Network network = gateway.getNetwork(CHANNEL_NAME);
//            Contract contract = network.getContract(CONTRACT_NAME);
//            byte[] result = contract.submitTransaction("queryCompanies");
//
////            ArrayList<String> arrayList = JSONObject.parseObject(new String(result), ArrayList.class);
////            ArrayList<Company> res = new ArrayList<>();
////            for (String s : arrayList) {
////                res.add(JSONObject.parseObject(new String(contract.submitTransaction("queryCompany",s)),Company.class));
////            }
////            return res;
//            return null ;
//        }
//    }

}
